package com.cx.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RunnablePool {
    public static void main(String[] args) {
        //最大线程数设置为5，队列最大能存3，使用主线程执行的拒绝策略
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 10,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
                new ThreadPoolExecutor.CallerRunsPolicy());

        /*
         * 测试
         * (1)当n<=5时 核心线程+任务队列=2+3=5,（2个在执行，3个在排队）
         * (2)当6<n<=8时 核心线程+任务队列+临时队列=2+3+(5-2)=8
         * (3)当n>8时,main线程执行任务
         *
         */
        int n = 5;
        for (int i = 0; i < n; i++) {
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10);
                        System.out.println("执行当前任务的线程：" + Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            // 提交任务
            threadPoolExecutor.execute(run);
        }
		//关闭线程池
        threadPoolExecutor.shutdown();
        //如果没有中断就一直等待
        while(!threadPoolExecutor.isTerminated()){  
        }
    }
}